//
//  NSNumber+XCategories.m
//  Foundation
//
//  Created by 吴新庭 on 2019/5/21.
//

#import "NSNumber+XCategories.h"

@implementation NSNumber (XCategories)

- (NSArray<NSNumber *> *)x_array {
    return [self x_arrayWithStep:@1 from:@0];
}

- (NSArray<NSNumber *> *)x_arrayWithStep:(NSNumber *)step from:(NSNumber *)begin {
    if (begin.integerValue >= self.integerValue) {
        return @[];
    }
    
    NSMutableArray *mArr = [NSMutableArray array];
    for (NSInteger i = begin.integerValue; i < self.integerValue; i += step.integerValue) {
        [mArr addObject:@(i)];
    }
    return mArr;
}

- (void)x_step:(void (^)(NSInteger, NSInteger))block {
    NSInteger total = self.integerValue;
    __block NSInteger current = 0;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0); // per sec
    dispatch_source_set_event_handler(_timer, ^{
        if (current >= total) {
            // end
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                block(current, total);
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(current, total);
            });
            current++;
        }
    });
    dispatch_resume(_timer);
}
@end
